import yaml
from sinodev import SinoDeviceType, SinoRTKCompatibility, SinoMSCompatibility


SNOW_CONFIG = {
    "device_type": SinoDeviceType.RTK,
    "device_compatibility": SinoRTKCompatibility.DEFAULT,
    "device_keywords": ["USB"],
    "serial_baudrate": 115200,
    "serial_timeout": 0.50,
    "sn_length": 9,
    "hwv_length": 3,
    "sn_tail_length": 4,
    "sn_tail_base": 10,
    "hwv_list": [],
}

g_cfg = SNOW_CONFIG.copy()


def resetcfg():
    global g_cfg
    g_cfg = SNOW_CONFIG.copy()


def readcfg(fp: str):
    global g_cfg
    with open(fp, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)
        g_cfg.update(config)

    g_cfg["device_type"] = SinoDeviceType(g_cfg["device_type"])
    if g_cfg["device_type"] == SinoDeviceType.RTK:
        g_cfg["device_compatibility"] = SinoRTKCompatibility(
            g_cfg["device_compatibility"]
        )
    if g_cfg["device_type"] == SinoDeviceType.MS:
        g_cfg["device_compatibility"] = SinoMSCompatibility(
            g_cfg["device_compatibility"]
        )

    if not g_cfg["device_keywords"]:
        g_cfg["device_keywords"] = ["USB"]

    g_cfg["sn_tail_step"] = f"{1:0{g_cfg["sn_tail_length"]}d}"
